<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="算法库id" prop="soId">
        <el-input v-model="queryParams.soId" placeholder="请输入算法库id" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="算法名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入算法名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleBatch">批量新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single"
          @click="handleUpdate">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple"
          @click="handleDelete">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="displayAlgoSkuList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="id" width="90" align="center" prop="id" />
      <el-table-column label="算法库id" width="90" align="center" prop="soId" />
      <el-table-column label="算法名称" align="center" prop="name" />
      <!-- <el-table-column label="备注" align="center" prop="remark" /> -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['segmentation:seg-base-sku:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['segmentation:seg-base-sku:removed']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改分割算法SKU对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="库id" prop="soId">
          <el-input v-model="form.soId" placeholder="请输入库id" />
        </el-form-item>
        <el-form-item label="sku名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入sku名称" />
        </el-form-item>
        <!-- <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 批量导入 -->
    <el-dialog :title="batchTitle" :visible.sync="batchOpen" width="700px" append-to-body>
      <div style="text-align: center;">
        模板：<ExportExcel :list="exportList" :tHeader="oHeader" :tValue="oValue" filename="导出模板下载">模板下载</ExportExcel>
      </div>
      <div style="text-align: center;margin-top: 5%;">
        <el-upload
        class="upload-demo"
          ref="upload"
          :limit="1"
          accept=".xlsx, .xls"
          action = "/"
          :on-change="handUploadExcel"
          :show-file-list="true"
          :disabled="upload.isUploading"
          :on-progress="handleFileUploadProgress"
          :auto-upload="false"
          drag  
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        </el-upload>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitFileForm">开始导入</el-button>

      </div>
      </el-dialog>
  </div>
</template>

<script>
import { listDisplayAlgoV5, getDisplayAlgoV5, addDisplayAlgoV5, updateDisplayAlgoV5, delDisplayAlgoV5,batchInsertDisplayAlgoV5 } from "@/api/genius/platform-display-algo-v5";
import ExportExcel from '@/components/ExcelUtils/Export2Excel.vue';
import { getToken } from '@/utils/auth';
import * as XLSX from 'xlsx';
export default {
  name: "platform-display-algo-v5",
  components: { ExportExcel },
  data() {
    return {
      selection:null,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      //批量新增弹窗
      batchOpen:false,
      //批量新增标题
      batchTitle:"",
      //上传的文件
      excelFileData:'',
      // 导出数据集合
      exportList: [{"soId":"946701","name":"冰红茶"}],
      // 导出样例的抬头和数据
      oHeader: ['库id','算法名称'],
      oValue:['soId','name'], 
      //批量导入上传
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/user/importData"
      },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 分割算法SKU表格数据
      displayAlgoSkuList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageIndex: 0,
        pageNum: 1,
        pageSize: 20,
        soId: null,
        name: null,
        orderByColumn:'id',
        isAsc:'desc'
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        soId: [
          { required: true, message: "库id不能为空", trigger: "blur" }
        ],
        name: [
          { required: true, message: "算法名称不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    handUploadExcel(file,fileList){
      // 校验文件
      if (!file) {
        this.$confirm("读取excel文件数据失败，请尝试重新上传文件！", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
        })
        // 如果没有文件 - 当然也可以提醒用户弹个警告框 但是基本没有这种情况的出现
        return false;
      }else if (!/\.(xls|xlsx)$/.test(file.name.toLowerCase())) {
        // 文件格式的判断
        this.$message.error("上传格式不正确，请上传xls或者xlsx格式");
        return false;
      }
      // 准备读取文件数据
      this.excelFileData = file
      this.$message.success("上传成功")
    },
    // // 文件上传成功处理
    // handleFileSuccess(response, file, fileList) {
    //   this.upload.open = false;
    //   this.upload.isUploading = false;
    //   this.$refs.upload.clearFiles();
    //   this.$alert(
    //     "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
    //       response.msg +
    //       "</div>",
    //     "导入结果",
    //     { dangerouslyUseHTMLString: true }
    //   );
    //   // this.getList();
    // },
    // 提交上传文件
    submitFileForm() {
      if(this.excelFileData){
        const fileReader = new FileReader(this.excelFileData);
        fileReader.onload = (ev) => {
          try {
            const data = ev.target.result;
            let workbook = XLSX.read(data, {
              type: "binary",
            });

            // 取第一张表
            const wsname = workbook.SheetNames[0];
            // 生成json表格内容
            let ws = XLSX.utils.sheet_to_json(workbook.Sheets[wsname]);
            // 循环 ws 取得其中的数据 
            // 把 ws 打印出来 就可以看得很清楚了 之后就进行自己想要的操作就可以了
            // 没有一样的代码 没有一样的需求
            
            if(ws.length>0){
                var temporary = [];
                for (let i = 0; i < ws.length; i++) {
                    let temp = {
                      soId:ws[i].库id,
                      name:ws[i].算法名称,
                    }
                    temporary.push(temp)
                }
                // 判断是否有重复的soId
                for(let i = 0; i < temporary.length; i++){
                  for(let j = i+1; j < temporary.length; j++){
                    if(temporary[i].soId === temporary[j].soId){
                      this.$message.warning("库id不能重复，请检查excel:"+temporary[i].soId)
                      return;
                    }
                  }
                }
                if(temporary.length === 0){
                  this.$message.warning("未读取合法数据，请检查excel")
                  return
                }
                this.$notify({
                  title: '提示',
                  message: '批量注册中,请稍后…',
                  offset: 700,
                  duration: 0
                });
                batchInsertDisplayAlgoV5(temporary)
                .then((res) => {
                  if(res.code === 200){
                    this.$message.success("注册成功,详情："+res.msg)
                    this.batchOpen = false
                    this.getList()
                  }else{
                    this.$message.warning("注册失败，原因："+res.msg)
                  }
                  this.$notify.closeAll();//去掉交互框
                  this.reset()
                })
                .catch((err) => {
                  this.$message.error('错误：'+err.message);
                }).finally(()=>{
                  this.$notify.closeAll();//去掉交互框
                  this.batchOpen = false
                  this.getList();
                  this.reset()
                  this.$refs.upload.clearFiles()
                })
             
            }else{
                this.$message({
                  type: "info",
                  message: "获取的列表为空，请检查表格是否有数据!",
                });
            }

          } catch (e) {
            return false;
          }
        };
        // 如果为原生 input 则应是 files[0]
        fileReader.readAsBinaryString(this.excelFileData.raw);
      }else{
        this.$message({
          type: 'warning',
          message: '请先上传Excel'
        })
      }
    },
    handleBatch(){
      this.reset();
      this.batchOpen = true;
      this.batchTitle = "批量新增算法SKU";
    },
    /** 查询陈列V5算法SKU列表 */
    getList() {
      this.loading = true;
      this.queryParams.pageIndex = this.queryParams.pageNum - 1;
      listDisplayAlgoV5(this.queryParams).then(response => {
        if (response.code === 200) {
          this.displayAlgoSkuList = response.data.data;
          this.total = response.data.totalCount;
        } else {
          this.$message.error("接口调用失败,原因：" + response.msg)
        }
      }).finally(() => {
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      if(this.batchOpen == true){
        this.$refs.upload.clearFiles()
      }
      this.open = false;
      this.reset();
      this.batchOpen = false;
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        soId: null,
        name: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.selection = selection;
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加陈列V5算法";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getDisplayAlgoV5(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改陈列V5算法";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateDisplayAlgoV5(this.form).then(response => {
              if (response.code === 200) {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }

            });
          } else {
            addDisplayAlgoV5(this.form).then(response => {
              if (response.code === 200) {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }

            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除陈列V5算法SKU编号为"' + ids + '"的数据项？').then(function () {
        // 修改为逻辑删除
        return delDisplayAlgoV5(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('segmentation/seg-base-sku/export', {
        ...this.queryParams
      }, `seg-base-sku_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
